using System;
using System.Configuration;

namespace ProgramMain.Properties {
    
    
    // This class allows you to handle specific events on the settings class:
    //  The SettingChanging event is raised before a setting's value is changed.
    //  The PropertyChanged event is raised after a setting's value is changed.
    //  The SettingsLoaded event is raised after the setting values are loaded.
    //  The SettingsSaving event is raised before the setting values are saved.
    internal sealed partial class Settings {
        
        public Settings() {
            // // To add event handlers for saving and changing settings, uncomment the lines below:

            this.SettingChanging += this.SettingChangingEventHandler;

            this.SettingsSaving += this.SettingsSavingEventHandler;
        }
        
        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) {
            // Add code to handle the SettingChangingEvent event here.
        }
        
        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) {
            // Add code to handle the SettingsSaving event here.
        }

        public static void ToggleConfigEncryption(bool bProtect)
        {
            // Takes the executable file name without the
            // .config extension.
            try
            {
                // Open the configuration file and retrieve 
                // the connectionStrings section.
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;

                if (bProtect != section.SectionInformation.IsProtected)
                {
                    if (section.SectionInformation.IsProtected)
                    {
                        // Remove encryption.
                        section.SectionInformation.UnprotectSection();
                    }
                    else
                    {
                        // Encrypt the section.
                        section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                    }
                    // Save the current configuration.
                    config.Save();
                }
            }
            catch (Exception)
            {
                //do nothing
            }
        }
    }
}
